package util

import (
	"github.com/gogf/gf/v2/database/gdb"

	"github.com/beherochuling/beesoft_api/app/dao"
)

func NewCirculate() *circulate {
	return &circulate{
		page:    1,
		perPage: 20,
		maxPage: 10,
	}
}

type circulate struct {
	page    int
	perPage int
	maxPage int
}

func (r *circulate) SetPerPage(perPage int) *circulate {
	r.perPage = perPage

	return r
}
func (r *circulate) SetMaxPage(maxPage int) *circulate {
	r.maxPage = maxPage

	return r
}

func (r *circulate) Iterator(m *gdb.Model, f func(record gdb.Record)) {
	for {
		items, err := m.
			Offset((r.page - 1) * r.perPage).
			Limit(r.perPage).
			All()
		if err != nil {
			panic(err)
		}

		if items != nil {
			for _, item := range items {
				f(item)
			}
		} else {
			break
		}

		r.page++
	}
}
func (r *circulate) IteratorByField(m *gdb.Model, f func(record gdb.Record)) {
	for {
		items, err := m.
			WhereGT(dao.Ips.Columns().Id, (r.page-1)*r.perPage).
			WhereLTE(dao.Ips.Columns().Id, r.page*r.perPage).
			All()
		if err != nil {
			panic(err)
		}

		if items != nil {
			for _, item := range items {
				f(item)
			}
		}

		r.page++
		if r.page > r.maxPage {
			break
		}
	}
}
